<?php
/**
 * 版权所有 (C) 2024 [陕西超拼软件科技有限公司]
 * 本产品使用《Apache-2.0》开源协议，除非遵守许可证（http://www.apache.org/licenses/LICENSE-2.0），否则不得使用
 * 未经许可禁止在本产品的整体或任何部分基础上以发展任何派生版本、修改版本或第三方版本用于重新分发
 * 具体说明可前往见闻间官网：https://cc.chaopin100.com/xinxuan 进行查看
 */
declare(strict_types=1);

namespace app\admin\service\auth;

use app\common\model\auth\AdminModel;
use app\common\model\auth\AdminRoleModel;
use app\common\model\auth\RolePermissionModel;
use Dengje\Pxy\BaseService;
use think\facade\Db;


class PermissionService extends BaseService
{

    private $menu = [];
    // private $permission = [];


    public function __construct()
    {


        $menu = cache('menu');
        if ($menu) {
            $this->menu = $menu;
        } else {
            $menu = $this->buildMenuHierarchy();
            $this->loopArrayWithChildren($menu);
            $this->sortTreeBySortField($menu);
            cache('menu', $menu);
            $this->menu = $menu;
        }


    }

    private function sortTreeBySortField(&$array, $key = "sort")
    {

        foreach ($array as $index => &$item) {
            if (!isset($item[$key])) {
                $item[$key] = 0; // 默认值为0
            }
        }


        if (!empty($array)) {
            // 使用usort和自定义比较函数进行排序
            usort($array, function ($a, $b) use ($key) {

                if ($a[$key] == $b[$key]) {
                    return 0;
                }
                return ($a[$key] < $b[$key]) ? -1 : 1;

            });
            foreach ($array as &$item) {
                // 递归排序子数组
                if (!empty($item['children'])) {
                    $this->sortTreeBySortField($item['children'], $key);
                }
            }
        }
    }



    /**
     * 菜单
     * @return array
     */
    public function getMenu($adminId)
    {

        return $this->filterMenu($this->menu, $adminId);

    }


    /**
     * 系统菜单
     * @return array
     */
    private function getSystemMenu()
    {

        $menu = include_once base_path() . 'menu.php';
        return $menu;
    }

    /**
     * 获取激活的插件菜单
     * @return array
     */
    private function getPluginMenu()
    {
        $plugins = app()->plugin->getPlug();

        // 获取所有激活的插件的菜单
        $pluginMenu = [];
        // var_dump(app()->plugin->getPlug());
        foreach ($plugins as $name => $plugin) {
            // var_dump($plugin['title']);
            $status = Db::name('plugin')->where('name', $name)->value('status');
            if (!empty($plugin->menu()) && $status == 1) {
                $pluginMenu = array_merge($pluginMenu, $plugin->menu());
            }


        }
        return $pluginMenu;
    }



    /**
     * 获取全部code
     */
    public function getAllCode()
    {

        return $this->collectCode($this->menu);

    }

    /**
     * 递归为一级
     * @param mixed $code
     * @return void
     */
    private function collectCode($tree)
    {

        foreach ($tree as $key => $value) {
            $array[] = $value['code'];
            if (isset($value['children']) && count($value['children']) > 0) {

                $array = array_merge($array, $this->collectCode($value['children']));


            }


        }
        return $array;
    }

    public function getPermission()
    {
        $menu = $this->menu;

        $menu = $this->buildMenuHierarchy($menu);

        $this->sortTreeBySortField($menu);
        return $menu;
    }
    // public function test($menus)
    // {
    //     $systemMenu = $this->getSystemMenu();
    //     $pluginMenu = $this->getPluginMenu();
    //     foreach ($pluginMenu as $key => $value) {
    //         if(!isset($value['parent']) || $value['parent'] == ''){
                
    //             $systemMenu[] = $value;
    //         }
    //     }
    //     $systemMenu = $this->flattenTree($systemMenu);
    //     halt($systemMenu);
    // }

    // 把插件菜单放到系统菜单内
    private function flattenTree($tree)
    {
        $pluginMenu = $this->getPluginMenu();

        $result = [];
        foreach ($tree as $item) {


            foreach ($pluginMenu as $key => $value) {

                if (isset($value['parent']) && $value['parent'] == $item['name']) {
                    $item['children'][] = $value;

                }

            }
            $result[] = $item;
            // 如果当前项有子菜单，递归展平子菜单
            if (isset($item['children']) && is_array($item['children'])) {

                $this->flattenTree($item['children']);
            }
        }


        return $result;
    }


    private function buildMenuHierarchy()
    {
        $systemMenu = $this->getSystemMenu();
        $pluginMenu = $this->getPluginMenu();

        foreach ($pluginMenu as $key => $value) {
            if(!isset($value['parent']) || $value['parent'] == ''){
                // var_dump($value);
                $systemMenu[] = $value;
            }
        }
        return $this->flattenTree($systemMenu);
    }

    // private function buildMenuHierarchy($menus)
    // {
    //     $menuStructure = [];
    //     $childrenMenus = [];

    //     foreach ($menus as $menu) {
    //         // 检查是否有父级菜单
    //         if (isset($menu['parent']) && $menu['parent'] !== '') {
    //             // 将子菜单添加到子菜单数组中
    //             $childrenMenus[] = $menu;
    //         } else {
    //             // 将顶级菜单添加到菜单结构中
    //             $menuStructure[] = $menu;
    //         }
    //     }


    //     // 构建子菜单结构
    //     foreach ($menuStructure as &$topMenu) {
    //         // 根据父级菜单名称查找子菜单
    //         foreach ($childrenMenus as $childMenu) {

    //             if ($childMenu['parent'] === $topMenu['name']) {
    //                 // 如果找到子菜单，添加到顶级菜单的 children 数组中
    //                 if (!isset($topMenu['children'])) {
    //                     $topMenu['children'] = [];
    //                 }
    //                 $topMenu['children'][] = $childMenu;
    //             }
    //         }
    //     }

    //     return $menuStructure;
    // }




    protected function loopArrayWithChildren(&$array)
    {
        foreach ($array as $key => &$value) {
            if (!isset($value['code'])) {
                $value['code'] = '';
            }
            if (isset($value['children']) && count($value['children']) > 0) {
                $this->loopArrayWithChildren($value['children']);
            } else {
                $value['children'] = [];
                if ($value['type'] == 2) {
                    unset($array[$key]);
                    continue; // 跳过当前循环迭代
                }

            }

        }

    }



    /**
     * 
     * 过滤没有权限的菜单
     * @param mixed $array
     * @return void
     */
    private function filterMenu(&$array, $adminId)
    {
        $admin = AdminModel::find($adminId);
        if ($admin->is_super != 1) {
            $roleIds = AdminRoleModel::where('admin_id', $adminId)->column('role_id');
            $codes = RolePermissionModel::whereIn('role_id', $roleIds)->column('code');
            foreach ($array as $key => &$value) {

                if (!in_array($value['code'], $codes)) {
                    unset($array[$key]);
                    $array = array_values($array);
                    continue; // 跳过当前循环迭代
                }
                if (isset($value['children']) && count($value['children']) > 0) {
                    $this->filterMenu($value['children'], $adminId);
                }

            }
        }

        return $array;

    }
}